<template>
   <div class="container">
        <div class="item">
            <span class="name">名称*</span>
            <input type="text" placeholder="请填写商品名称" v-model="shop.title">
        </div>
        <div class="item">
            <span class="name">标签</span>
            <input type="text" placeholder="请填写商品标签，多个标签逗号分隔" id="sign" v-model="shop.sign">
        </div>
        <div class="item">
            <span class="name">地址*</span>
            <input type="text" placeholder="请填写地址" id="address" v-model="shop.address">
        </div>
        <div class="item" @click="showCate=true">
            <span class="name">分类*</span>
            <p>{{cate==''?'请选择分类':cate.cate_name}}</p>
        </div>
        <!-- <div class="item">
          <span>是否包邮</span>
          <van-radio-group v-model="shop.send_type" direction="horizontal">
            <van-radio name="1"> 是</van-radio>
            <van-radio name="0">否 </van-radio>
          </van-radio-group>
      
       </div> -->
        <div class="item">
            <span>型号</span>
            <div class="btn btn-add" @click="add">+</div>
           
        </div>
         <div class="items" v-for="(item,index) in sizes" :key="index">
              <input type="text" name="size_name" v-model="item.size_name" placeholder="请填写型号">
              <input type="text" name="size_num" v-model="item.size_num" placeholder="请填写数量" maxlength="7">
              <div class="des" @click="des(index)">-</div>
            </div>
        <div class="item">
            <span>主图</span>
            <div class="btn btn-add"  @click="uploadfile">+</div>
        </div>
        <p class="des"> 为了更好地展示商品，建议上传400px*300px尺寸</p>
        <div class="imgs">
          <div class="img" v-for="(item,index) in default_img" :key="index">
            <img :src="item">
            <van-icon name="cross" class="close"  @click="delteImg(index)"/>
          </div>
        </div>
        <div class="item">
            <span>详情</span>

        </div>
        <div class="item" id="editorContainer">
            
        </div>
       <van-popup v-model="showCate" 
        position="bottom"
        :style="{ height: '30%' }">
        <van-picker
          show-toolbar
          :columns="cates"
          value-key="cate_name"
          @cancel="showCate = false"
          @confirm="onConfirm"
        />
      </van-popup>
       <input type="file" ref="zhizhao"  id="zhizhao" style="opacity: 0;width:0;"   @change="upload($event)">
    </div>
</template>

<script>

import {Toast} from 'vant'
export default {
  name: 'HelloWorld',
  data () {
    return {
     shop:'',
     showCate:false,
     sizes:[],
     cates:[],
     cate:'',
     default_img:[],
     editor:'',
     api_token:'',
     id:'',
     saveF:true
    }
  },
  methods:{
    des(index){
      this.sizes.splice(index,1)
    },
    delteImg(index){
      this.default_img.splice(index,1);
    },
    add(){
      this.sizes.push({
        size_name:"",
        size_num:1
      })
    },
     onConfirm(value) {
      this.cate = value;
      this.showCate = false;
    },
    getCates(){
      var v= this;
      $.ajax({
        url:'https://www.qibaowangguo.com/api/get_cates?p=w',
        type:"get",
        success:function(res){
          console.log(res)
          v.cates = res.data;
        }
      })
    },
    uploadfile(){
      this.$refs.zhizhao.click();
    },
    upload(event){
      var that = this;
      var img_id=document.getElementById('zhizhao').value; //根据id得到值
      var index= img_id.indexOf("."); //（考虑严谨用lastIndexOf(".")得到）得到"."在第几位
      img_id=img_id.substring(index); //截断"."之前的，得到后缀
      if(img_id!=".bmp"&&img_id!=".png"&&img_id!=".gif"&&img_id!=".jpg"&&img_id!=".jpeg"){  //根据后缀，判断是否符合图片格式
         return Toast('请选择图片类型文件') 
         document.getElementById('zhizhao').value="";  // 不符合，就清除，重新选择
      }
     
      var files = event.target.files[0];
     
      this.checkImg(files);
       
   },
   checkImg(files){
    var that = this;
    var formdata = new FormData();
    formdata.append('p','w');
    formdata.append('file',files);
    $.ajax({
        url:'https://www.qibaowangguo.com/api/check_msg',
        data:formdata,
        type:"post",
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头, jquery 会自动设置为multipart/form-data
        contentType : false,
        success:function(res){
          console.log(res);
            if(res.status==1){
              Toast('上传成功');
               that.default_img.push(res.data)
            }else{
                Toast(res.msg)
            }
        }
    })
                
            
      
   },
    getUrlKey:function(name){
    return decodeURIComponent((new RegExp('[?|&]'+name+'='+'([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+/g,'%20'))||null;
   },
   initEditor(){
     var that = this;
     this.editor =  new ZxEditor('#editorContainer', {
        editable: true,
        cursorColor: 'red',
        btnClass:'save',
        showMsg:function(msg){
          Toast(msg)
        }
      })
      document.getElementById('saveBtn').addEventListener('click',function(){
         that.saveGoods();
      })
    },
    getGoodDetail(id){
      var that = this;
      $.ajax({
        url:"https://www.qibaowangguo.com/api/getGoodsDetail",
        data:{
          p:"w",
          id:this.id
        },
        type:"get",
        success:function(res){
          that.shop = res.data;
          if(res.data.sizes!=""){
           var sizes =JSON.parse(
            res.data.sizes);
            that.sizes = sizes;
           
          }
          that.default_img = res.data.default_img;
           that.cates.map(item=>{
             if(item.cate_id==res.data.cate_id){
               that.cate = item
             }
           })
           that.shop.send_type = res.data.send_type.toString();
           that.editor.setHtml(res.data.content);
           window,scrollTo(0,0)
        }
      })
    },
    saveGoods(){
      if(this.shop.title==''){
        return Toast('请填写商品标题')
      }
      if(this.shop.address==''){
        return Toast('请填写商品地址')
      }
      if(this.cate==''){
        return Toast('请选择商品分类')
      }
      if(this.default_img.length==0){
        return Toast('请上传商品图片')
      }
      var content = this.editor.getHtml();
      var total = 0;
      if(this.sizes.length>0){
        this.sizes.map(item=>{
          if(item.size_name==''){
            return Toast('请填写型号名称')
          }
          if(item.size_num==''){
            return Toast('请填写尺寸数量')
          }
        total += Number(item.size_num)
        })
      }
      if(this.saveF){
        this.saveF = false;
        var that = this;
      $.ajax({
        url:"https://www.qibaowangguo.com/api/goods_save",
        data:{
          p:"w",
          id:this.id,
          api_token:this.api_token,
          title:this.shop.title,
          address:this.shop.address,
          cate_id:this.cate.cate_id,
          sign:this.shop.sign,
          default_img:this.default_img.join(','),
          sizes:JSON.stringify(this.sizes),
          send_type:this.shop.send_type,
          total:total,
          content:content
        },
        type:"post",
        success:function(res){
          console.log(res);
          if(res.status==1){
            Toast('保存成功');
            wx.miniProgram.navigateBack({
              
            });
            return false;
            
          }else{
            Toast(res.msg);
            that.saveF = true;
          }
        },
        error:function(error){
          console.log(error)
        }
      })
       }
    }
  },
  mounted(){
    this.getCates();
    this.initEditor();
    this.id = this.getUrlKey('id');
    this.api_token = this.getUrlKey('api_token');
    if(this.id!=0){
      this.getGoodDetail(this.id)
    }else{
      this.shop={
        title:"",
        address:"",
        sign:"",
        send_type:1
      }
    }
    console.log(wx);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.container{
  padding:12px;
}
.item{
  font-size:12px;
  color:#000;
  display:flex;
  margin-bottom:20px;
}
.item span{
  display:inline-block;
  font-size:14px;
  font-weight:500;
  margin-right:10px;
  vertical-align: middle;
  line-height: 32px;
}
.item p{
  line-height:32px;
}
.des{
  color:#888;
  font-size:12px;
}
.item input{
  height:30px;
  padding:0 10px;
  font-size:14px;
  display: inline-block;
  width:80%;
  border:1px solid #ccc;
  background:#fff;
  border-radius: 5px;
}
.item input::placeholder,.items input::placeholder{
  color:#888888;
}
.item input:focus,.items input:focus{
  border-color:#C02C38;
  outline: 0 none;
}
.items {
  padding-left:34px;
  display:flex;
  margin-bottom:10px;
}
.items input{
  flex:1;
  margin:0 5px;
  height:30px;
  padding:0 10px;
  font-size:14px;
  display: inline-block;
  width:80%;
  border:1px solid #ccc;
  background:#fff;
  border-radius: 5px;
}
.items .des{
  width:20px;
  height:20px;
  line-height:20px;
  margin-top:5px;
  text-align:center;
  color:#fff;
  background:#ccc;
  border-radius:50px;
}
.imgs{
  overflow:hidden;
}
.img{
  width:240px;
  height:147px;
  position:relative;
}
.img img{
  width:100%;
  height:100%;
}
.close{
  position:absolute;
  top:5px;
  right:5px;
  width:20px;
  height:20px;
  text-align:center;
  line-height:20px;
  border-radius:50%;
  background:#ccc;
  color:#fff;
}
.btn-add{
  width:40px;
  height:32px;
  color:#fff;
  text-align:center;
  line-height:32px;
  border-radius:5px;
  background:#C02C38;
}
.save{
  position:fixed;
  z-index:999;
  bottom:0;
  right:0;
  font-size:14px;
  width:80px;
  height:50px;
  line-height:50px;
  text-align:center;
  background:#C02C38;
  color:#fff;
}
</style>
